#include "npcWindow.h"
#include <QDebug>
#include <QMessageBox>
#include <QListIterator>
#include <QFile>
#include <QFileDialog>
#include <QRegExp>
#include <QProcess>
#include <QSettings>
#include <QtAlgorithms>

void npcWindow::listModified(){
    npc * p = 0, * q = 0;
    qSort(proxies.begin(), proxies.end(), qGreater<npc *>() );
    qDebug() << "sorting ... ";
    QMutableListIterator<npc*>  i(proxies);
    if (i.hasNext())
	p = i.next();
    while (i.hasNext()){
	q = i.next();
	if (p->ip() == q->ip())
	    i.remove();
	else
	    p = q;
    }
    model->fresh();
    //npcView->resizeColumeToContents(0);
}

bool npcWindow::extract(const QByteArray & lineData){
    qDebug() << lineData;
    QRegExp exp("(\\d{2,3}(\\.\\d{1,3}){3}):([^@]*)@?([^#@]*)#?([^#]*)");
    int pos = exp.indexIn(lineData, 0);
    npc * p = 0;
    if (pos != -1){
	if (exp.cap(4).compare("SOCKS5") == 0)
	    p = new npc(QNetworkProxy::Socks5Proxy, exp.cap(1), exp.cap(3).toInt(), exp.cap(5));
	else
	    p = new npc(QNetworkProxy::HttpProxy, exp.cap(1), exp.cap(3).toInt(), exp.cap(5));
	proxies.push_back(p);
	return true;
    }
    return false;
}

npcWindow::npcWindow(QWidget * parent):QWidget(parent){
    setupUi(this);
    model = new npcModel(this);
    model->setSource(&proxies);
    freshTimer = new QTimer(this);
    npcView->setModel(model);
    connect (freshTimer, SIGNAL(timeout()), npcView, SLOT(reset()));
    readSettings();
    listModified();
    freshTimer->start(1000);
}

npcWindow::~npcWindow(){
}

void npcWindow::on_start_clicked(){
    QWidget parent;
    if (lineEditTarget->text() == ""){
	setting->setChecked(true);
	QMessageBox::warning(&parent, tr("Warning"), tr("Please write a target.\t\t"));
	return;
    }
    if (lineEditKey->text() == ""){
	setting->setChecked(true);
	QMessageBox::warning(&parent, tr("Warning"), tr("Please write a key word.\t\t"));
	return;
    }
    QListIterator<npc*>  i(proxies);
    while (i.hasNext()){
	i.next()->start(lineEditTarget->text(), lineEditKey->text());
    }
}

void npcWindow::on_clear_clicked(){
    npc * p = 0;
    QMutableListIterator<npc*>  i(proxies);
    while (i.hasNext()){
	p = i.next();
	if (p->time() == p->time(-1))
	    i.remove();
    }
    listModified();
}

void npcWindow::on_save_clicked(){
}

void npcWindow::on_load_clicked(){
    int count = 0;
    QString fileName = QFileDialog::getOpenFileName(this, tr("Choose proxy list"));
    if (fileName == "") return;
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
	return;
    while (!file.atEnd()) {
	if (count == 10000) break;
	QByteArray line = file.readLine();
	line.chop(1);
	if (extract(line)) count ++;
    }
    QWidget tempWidget;
    QMessageBox::information(&tempWidget, tr("Load Result"),
			      tr("New add:\t\t\t%1\nTotal:\t\t\t%2").arg(count) .arg( proxies.size()));
    listModified();
}

void npcWindow::on_set_clicked(){
    npc * p = proxies.at(npcView->currentIndex().row());
    QObject parent;
    QString program = "export";
    QStringList arguments;
    arguments << tr("http_proxy=\"%1\"").arg(p->ip());
    QProcess *myProcess = new QProcess(&parent);
    myProcess->start(program, arguments);
    qDebug() << program << " " << arguments;
}

void npcWindow::on_quit_clicked(){
}

void npcWindow::saveSettings(){
    QSettings settings ("HUST::CS FRE.", "NPC");
    settings.beginGroup("npcWindow");
    settings.setValue("geometry", saveGeometry());
    settings.setValue("target", lineEditTarget->text());
    settings.setValue("key", lineEditKey->text());

    settings.setValue("count", proxies.count());
    QListIterator<npc*>  i(proxies);
    int count = 0;
    while (i.hasNext()){
	settings.setValue(tr("proxy.%1").arg(count ++), i.next()->save());
    }
    settings.endGroup();
}

void npcWindow::readSettings(){
    QSettings settings ("HUST::CS FRE.", "NPC");
    settings.beginGroup("npcWindow");
    restoreGeometry(settings.value("geometry").toByteArray());
    lineEditTarget->setText(settings.value("target", "").toString());
    lineEditKey->setText(settings.value("key", "").toString());
    int count = settings.value("count", 0).toInt();
    while (count -- > 0)
	extract(settings.value(tr("proxy.%1").arg(count)).toByteArray());
    settings.endGroup();
}

void npcWindow::closeEvent(QCloseEvent * event){
    saveSettings();
    event-> accept();
}

